import {onMounted, ref, watch, watchEffect} from "vue";
import type {DictCategoryType, InfoType} from "@/util/publicType";
import {dictCategory, dictDetail, info} from "@/api/api";
import type {AxiosResponse} from "axios";
import {message} from "ant-design-vue";

export const useDictCategory = () => {
    // 分类
    const categoryState = ref<DictCategoryType[]>([]);
    // menu数据
    const menuData = ref<DictCategoryType[]>([]);
    // vue监听不到异步全局存储的变化，单独请求info，判断权限
    onMounted(async () => {
        try {
            const resInfo = await info();
            const resDict = await dictCategory();
            const infoData: InfoType = resInfo.data.data.data;
            const dictData = resDict.data.data.data;
            categoryState.value = dictData;
            const menu: DictCategoryType[] = []
            for (const v of dictData) {
                const r = await dictDetail(v.id);
                if (infoData.jurisdictions.findIndex(item => item.name === v.name) >= 0) {
                    menu.push(v);
                    v.child = r.data.data.data;
                }
            }
            menuData.value = menu;
        } catch (err) {
            message.success(err as string)
        }
    });
    return {categoryState, menuData}
}